<template>
  <div v-loading="loading">
    <el-collapse-transition>
      <div v-show="!isShowDetail" class="app-main-content-box">
        <app-main-title title="预订记录" />

        <!--filter区域-->
        <div>
          <el-form
            ref="filterForm"
            :model="filterForm"
            label-width="100px"
            size="small"
          >
            <el-form-item
              label="选择时间："
              :rules="[{ required: true, message: '时间区间不能为空' }]"
              prop="customParamsDate"
              style="display: inline-block; margin-right: 10px"
            >
              <el-select
                v-model="filterForm.timeType"
                placeholder="请选择时间类型"
                style="width: 110px"
              >
                <el-option label="预订时间" :value="1" />
                <el-option label="入住时间" :value="2" />
              </el-select>
              <el-date-picker
                v-model="filterForm.customParamsDate"
                size="small"
                value-format="yyyy-MM-dd"
                format="yyyy-MM-dd"
                type="daterange"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                placeholder="选择日期"
                style="width: 250px"
              />
            </el-form-item>

            <el-form-item
              label="手机号："
              style="display: inline-block"
              prop="checkInPhone"
            >
              <el-input
                v-model="filterForm.checkInPhone"
                placeholder="请输入手机号"
                style="width: 250px"
              />
            </el-form-item>

            <el-form-item
              label="单号查询："
              style="display: inline-block"
              prop="orderNo"
            >
              <el-input
                v-model="filterForm.orderNo"
                placeholder="请输入订单号"
                style="width: 250px"
              />
            </el-form-item>

            <!-- 筛选 -->
            <div class="app-main-filter-collapse-box filter">
              <el-collapse>
                <el-collapse-item
                  ref="filterCollapse"
                  title="按条件筛选"
                  name="1"
                >
                  <el-form-item label="支付方式：" prop="paymentMethod">
                    <el-radio-group v-model="filterForm.paymentMethod">
                      <el-radio label>全部</el-radio>
                      <el-radio
                        v-for="item in paymentOptions"
                        :key="item.key"
                        :label="item.key"
                      >{{ item.label }}</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item label="订单状态：" prop="subStatus">
                    <el-radio-group v-model="filterForm.subStatus">
                      <el-radio label>全部</el-radio>
                      <template v-for="(item, index) in subStatusOptions">
                        <el-radio :key="index" :label="index">
                          {{ item }}
                        </el-radio>
                      </template>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item label="订单类型：" prop="subTypes">
                    <el-select
                      v-model="filterForm.subTypes"
                      placeholder="请选择"
                      style="width: 400px"
                    >
                      <el-option
                        v-for="(item, index) in subTypesSelectOptions"
                        :key="index"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="门店：" prop="shopId">
                    <el-select
                      v-model="filterForm.shopId"
                      filterable
                      placeholder="可通过名称搜索"
                      style="width: 400px"
                    >
                      <el-option
                        v-for="(item, index) in $store.state.user
                          .allManageShopFilterOptions"
                        :key="index"
                        :label="item.name"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-collapse-item>
              </el-collapse>
            </div>

            <el-form-item class="filter-btn">
              <el-button
                type="primary"
                round
                @click="submitForm('filterForm')"
              >查 询</el-button>
              <el-button
                round
                @click="resetForm('filterForm')"
              >重 置</el-button>
              <el-button
                v-if="
                  !$store.getters.banBtnList.includes('MCH_BTN_BK_FD_EXPORT') ||
                    !$store.getters.banBtnList.includes('MCH_BTN_BK_HR_EXPORT') ||
                    !$store.getters.banBtnList.includes('MCH_BTN_BK_KTV_EXPORT')
                "
                round
                @click="downExcel"
              >导 出</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 统计卡片 start -->
        <div>
          <AppTableStatisticsCard :statistics-card-data="statisticsCardData" />
        </div>
        <!-- 统计卡片 end -->

        <div>
          <!-- 表格内容 -->
          <div class="list-table">
            <el-table
              size="small"
              :data="list"
              border
              stripe
              style="width: 100%"
              empty-text="暂无数据"
            >
              <el-table-column prop="createTime" label="下单时间" width="150" />
              <el-table-column prop="orderNo" label="订单号" width="150" />
              <el-table-column prop="subStatus" label="订单状态" width="100">
                <template slot-scope="scope">
                  {{ subStatusOptions[scope.row.subStatus] }}
                </template>
              </el-table-column>
              <el-table-column prop="subType" label="订单类型" width="80">
                <template slot-scope="scope">
                  {{
                    scope.row.bizData.alias || subTypeOptions[scope.row.subType]
                  }}
                </template>
              </el-table-column>
              <el-table-column prop="customerName" label="预订人" width="150">
                <template slot-scope="scope">
                  <span
                    v-for="(item, index) in scope.row.bizData.checkInList"
                    :key="index"
                    class="list-item"
                  >
                    <span v-if="index !== 0">&nbsp;|&nbsp;</span>
                    {{ item }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column
                prop="bizData.checkInPhone"
                label="手机号"
                width="150"
              />
              <el-table-column prop="title" label="资源名称" width="120" />
              <el-table-column prop="bizData.num" label="资源数量" width="80" />
              <el-table-column
                prop="bizData.beginDay"
                label="到店日期"
                width="120"
              />
              <el-table-column
                prop="bizData.arrivalTime"
                label="到店时间"
                width="120"
              />
              <el-table-column
                prop="bizData.endDay"
                label="离店日期"
                width="120"
              />
              <el-table-column label="订单原价/元" width="100">
                <template slot-scope="scope">
                  <span>{{ scope.row.totalFee / 100 }}</span>
                </template>
              </el-table-column>
              <el-table-column label="优惠金额/元" width="100">
                <template slot-scope="scope">
                  <div
                    v-if="
                      !scope.row.useDiscount && !scope.row.usePointsDiscount
                    "
                  >
                    无
                  </div>
                  <div v-else>
                    {{
                      (scope.row.discountFee + scope.row.pointsDiscountFee) /
                        100
                    }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="订单金额/元" width="100">
                <template slot-scope="scope">
                  <span>
                    {{
                      (scope.row.totalFee -
                        scope.row.discountFee -
                        scope.row.pointsDiscountFee) /
                        100
                    }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column
                prop="paymentMethod"
                label="结账方式"
                width="100"
              >
                <template slot-scope="scope">
                  <span>在线支付</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="paymentMethod"
                label="支付方式"
                width="100"
              >
                <template slot-scope="scope">{{
                  scope.row.payFee == 0 ? '其他' : paymentKeyOptions[scope.row.paymentMethod]
                }}</template>
              </el-table-column>
              <el-table-column prop="shopName" label="门店" />
              <el-table-column label="操作" fixed="right">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    size="mini"
                    round
                    @click="openOrderDetail(scope.row)"
                  >详情</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页 -->
            <pagination-direction
              v-if="paginationConfig.total !== 0"
              :config="paginationConfig"
              @sizeschange="sizesChange"
              @pagechange="pageChange"
            />
          </div>
        </div>
      </div>
    </el-collapse-transition>

    <!-- 入账详情 -->
    <el-collapse-transition>
      <order-detail v-show="isShowDetail" ref="orderDetail" />
    </el-collapse-transition>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { downExportBookingOrders } from '@/api/download'
import { getOrderRecord, getOrderStats } from '../../api/record'
import OrderDetail from '../components/OrderDetail'
export default {
  components: {
    OrderDetail
  },
  data() {
    return {
      // 配置
      // 分页配置
      paginationConfig: {
        direction: 'center', // 分页位置
        layout: 'total, sizes, prev, pager, next, jumper', // 分页类型
        pageSizes: [10, 20], // 分页pages
        total: 0,
        page: 1, // 页数-默认1
        pageSize: 10 // 每页条数-默认10
      },
      subTypesSelectOptions: [
        {
          label: '所有',
          value: 'all'
        }
      ],
      subTypeOptions: {
        0: '全日房',
        1: '钟点房',
        2: 'KTV房'
      },
      subStatusOptions: [
        '待支付',
        '待确认',
        '待消费',
        '已消费',
        '支付超时',
        '超时未确认',
        '用户取消支付',
        '用户已取消',
        '商家已取消',
        '已过期'
      ],
      // 状态
      loading: false, // 表格loading
      isShowDetail: false,
      // 数据
      statisticsCardData: [],
      list: [], // 表格数据
      filterForm: {
        shopId: '',
        timeType: 1,
        customParamsDate: [
          this.$momentMini().format('YYYY-MM-DD'),
          this.$momentMini().format('YYYY-MM-DD')
        ],
        paymentMethod: '',
        subStatus: '',
        subTypes: 'all'
      },
      subTypesAuthOptions: []
    }
  },
  computed: {
    ...mapGetters(['paymentOptions', 'paymentKeyOptions']),
    msgGetOrderNo() {
      return this.$store.state.message.msgGetOrderNo
    }
  },
  watch: {
    msgGetOrderNo() {
      this.openMsgOrderInfo()
    }
  },
  mounted() {
		console.log('$store.state.user.allManageShopFilterOptions',this.$store.state.user.allManageShopFilterOptions)
    // 全日房权限
    if (!this.$store.getters.banBtnList.includes('MCH_CARD_BK_FD_ORDER_FORM')) {
      this.subTypesAuthOptions.push(0)
      this.subTypesSelectOptions.push({
        label: '全日房',
        value: '0'
      })
    }

    // 钟点房权限
    if (!this.$store.getters.banBtnList.includes('MCH_CARD_BK_HR_ORDER_FORM')) {
      this.subTypesAuthOptions.push(1)
      this.subTypesSelectOptions.push({
        label: '钟点房',
        value: '1'
      })
    }

    // KTV权限
    if (
      !this.$store.getters.banBtnList.includes('MCH_CARD_BK_KTV_ORDER_FORM')
    ) {
      this.subTypesAuthOptions.push(2)
      this.subTypesSelectOptions.push({
        label: 'KTV',
        value: '2'
      })
    }
    this.fetchData()
    this.openMsgOrderInfo()
    this.openMsgOrder()
  },
  methods: {
    openMsgOrder() {
      const arrFrom = ['invoice', 'cancelTable']
      this.$route.query.orderNo && arrFrom.indexOf(this.$route.query.from) > -1 && this.openOrderDetail({ orderNo: this.$route.query.orderNo })
    },
    openMsgOrderInfo() {
      // 订单消息跳转过来后弹窗
      const { orderNo, path } = this.msgGetOrderNo
      const isCan = this.$route.path === path
      if (orderNo && isCan) {
        this.openOrderDetail({ orderNo })
        this.$store.dispatch('SetMsgOrderNo', {})
        // this.filterForm.orderNo = ''
      }
    },
    /**
     * 获取数据
     */
    // 获取列表
    fetchData(
      page = this.paginationConfig.page,
      pageSize = this.paginationConfig.pageSize
    ) {
      this.$refs.filterForm.validate(async(valid) => {
        if (valid) {
          this.loading = true
          const params = this.setRequestParams()
          params.pageNum = page
          params.pageSize = pageSize
          Promise.all([this.getList(params), this.getCount(params)]).then(
            (res) => {
              this.loading = false
            }
          )
        }
      })
    },

    // 获取筛选数据
    setRequestParams() {
      let params = {}
      params = Object.assign({}, this.filterForm)
      if (params.timeType === 1) {
        params.beginTime = params.customParamsDate[0]
        params.endTime = params.customParamsDate[1]
      } else {
        params.arrivalDayBegin = params.customParamsDate[0]
        params.arrivalDayEnd = params.customParamsDate[1]
      }
      delete params.customParamsDate
      if (params.subTypes === 'all') {
        params.subTypes = this.subTypesAuthOptions
      } else {
        params.subTypes = [params.subTypes]
      }
      // 暂时解决门店id权限问题 不是总部强制查询当前门店id
      if (this.$store.state.user.shopId !== 0) {
        params.shopId = this.$store.state.user.shopId
      }
      // 清除多余字段
      for (const key in params) {
        if (params[key] === '' || params[key] === 'all') {
          delete params[key]
        }
      }
      return params
    },

    // 获取列表
    getList(params) {
      return new Promise((resolve, reject) => {
        getOrderRecord(params)
          .then((res) => {
            let list = res.data.list
            list = list.map((value) => {
              if (value.bizData) {
                value.bizData = JSON.parse(value.bizData)
                value.bizData.customDays = Object.keys(
                  value.bizData.roomPrices
                ).length
              }
              return value
            })
            this.paginationConfig.total = res.data.total
            this.paginationConfig.page = res.data.pageNum
            this.list = list
          })
          .finally(() => {
            resolve()
          })
      })
    },

    // 获取统计
    getCount(params) {
      return new Promise((resolve, reject) => {
        if (params.pageNum !== 1) {
          resolve()
        } else {
          this.statisticsCardData = [
            {
              title: '待消费订单 / 元',
              value: 0,
              describeList: [],
              detailList: ['笔数：0', '优惠：￥0', '单均：￥0']
            },
            {
              title: '已消费订单 / 元',
              value: 0,
              describeList: [],
              detailList: ['笔数：0', '优惠：￥0', '单均：￥0']
            },
            {
              title: '商家已取消订单 / 元',
              value: 0,
              describeList: [],
              detailList: ['笔数：0', '优惠：￥0', '单均：￥0']
            },
            {
              title: '用户已取消订单 / 元',
              value: 0,
              describeList: [],
              detailList: ['笔数：0', '优惠：￥0', '单均：￥0']
            },
            {
              title: '已过期订单 / 元',
              value: 0,
              describeList: [],
              detailList: ['笔数：0', '优惠：￥0', '单均：￥0']
            }
          ]
          getOrderStats(params)
            .then((res) => {
              console.log('请求获取统计--', res)
              const indexObj = {
                2: 0,
                3: 1,
                8: 2,
                7: 3,
                9: 4
              }
              console.log('indexObj--', indexObj)
              res.data.forEach((v) => {
                console.log('v--', v)
                switch (v.subStatus) {
                  case 2:
                  case 3:
                  case 8:
                  case 7:
                  case 9:
                    console.log('v.subStatus--', v.subStatus)
                    const index = indexObj[v.subStatus]
                    console.log('index--', index)
                    this.statisticsCardData[index].value = v.totalFee / 100
                    this.statisticsCardData[index].detailList = [
                      `笔数：${v.num}`,
                      `优惠：￥${(v.discountFee + v.pointsDiscountFee) / 100}`,
                      `单均：￥${this.$math.div(v.totalFee / v.num, 100, 2)}`
                    ]
                    break
                }
              })

              console.log('已获取统计--', this.statisticsCardData)
            })
            .finally(() => {
              resolve()
            })
        }
      })
    },

    // 分页sizes改变
    sizesChange() {
      this.fetchData()
    },

    // 分页page改变
    pageChange() {
      this.fetchData()
    },

    /**
     * 按钮组
     */
    // 导出
    downExcel() {
      this.$refs.filterForm.validate((valid) => {
        if (valid) {
          const params = this.fetchFilterParams()
          downExportBookingOrders(params)
            .then((res) => {
              if (res.code === 0) {
                this.$alert(
                  '数据导出中，请稍后到数据下载中心进行下载',
                  '提示',
                  {
                    confirmButtonText: '确定',
                    center: true,
                    type: 'success',
                    callback: (action) => {}
                  }
                )
              }
            })
            .catch((err) => {})
        }
      })
    },

    // 查询
    submitForm() {
      this.fetchData(1)
    },

    // 重置
    resetForm(formName) {
      console.log('formName', formName)
      this.$refs[formName].resetFields()
    },

    // 跳转详情
    openOrderDetail(row) {
      this.isShowDetail = true
      this.$refs.orderDetail.open({ orderNo: row.orderNo }).then((res) => {
        this.isShowDetail = false
        this.fetchData()
      })
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.filter-btn {
  margin-bottom: 20px;
}
/* 换行 */
.el-radio + .el-radio {
  margin-left: 0;
}
.el-radio {
  margin-right: 10px;
  line-height: 32px;
}
</style>
